博客
关于我
SpringMVC(16)——文件下载
阅读量:250 次
发布时间:2019-03-01

本文共 6276 字,大约阅读时间需要 20 分钟。

Spring MVC 文件上传与下载实现

1. 文件上传

1.1 创建 controller 类

package controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.List;@Controllerpublic class FileDownController {    @RequestMapping("/showDownFiles")    public String showDownFiles(HttpServletRequest request, Model model) {        String realPath = request.getServletContext().getRealPath("/fileUpload/temp/");        File dir = new File(realPath);        File[] files = dir.listFiles();        ArrayList
fileNameList = new ArrayList<>(); for (int i = 0; i < files.length; i++) { fileNameList.add(files[i].getName()); } model.addAttribute("files", fileNameList); return "showDownFiles"; } @RequestMapping("/down") public String down(@RequestParam String filename, HttpServletRequest request, HttpServletResponse response) { try { String filePath = request.getServletContext().getRealPath("/fileUpload/temp/"); response.setHeader("Content-Type", "application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" + toUTF8String(filename)); FileInputStream fis = new FileInputStream(filePath + "\\" + filename); ServletOutputStream sos = response.getOutputStream(); byte[] b = new byte[1024]; int aRead = 0; while ((aRead = fis.read(b)) != -1) { sos.write(b, 0, aRead); } sos.flush(); fis.close(); sos.close(); } catch (IOException e) { e.printStackTrace(); } return null; } public String toUTF8String(String str) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c >= 0 && c <= 255) { sb.append(c); } else { try { byte[] b = Character.toString(c).getBytes("UTF-8"); for (int j = 0; j < b.length; j++) { int k = b[j]; if (k < 0) { k = 255; } sb.append("%" + Integer.toHexString(k).toUpperCase()); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); sb.append("%" + Integer.toHexString(c)); } } } return sb.toString(); }}

1.2 创建 upload controller 类

package controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.multipart.MultipartFile;import pojo.UploadFile;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.File;import java.io.IOException;import java.util.List;@Controllerpublic class FileUploadController {    @RequestMapping("/upload")    public String upload(@ModelAttribute UploadFile uploadFile, HttpServletRequest request, HttpServletResponse response) {        String realPath = request.getServletContext().getRealPath("/fileUpload/temp/");        File targetDir = new File(realPath);        if (!targetDir.exists()) {            targetDir.mkdirs();        }        List
files = uploadFile.getMyfile(); for (int i = 0; i < files.size(); i++) { MultipartFile multipartFile = files.get(i); String originalFilename = multipartFile.getOriginalFilename(); File targetFile = new File(realPath, originalFilename); try { multipartFile.transferTo(targetFile); } catch (IOException e) { e.printStackTrace(); } } return "success"; }}

1.3 创建 UploadFile 类

package pojo;import org.springframework.web.multipart.MultipartFile;import java.util.List;public class UploadFile {    private List
myfile; public List
getMyfile() { return myfile; } public void setMyfile(List
myfile) { this.myfile = myfile; }}

2. 文件下载

2.1 设置正确的 MIME 类型

response.setHeader("Content-Type", "application/x-msdownload");

2.2 设置正确的 Content-Disposition 头

response.setHeader("Content-Disposition", "attachment; filename=" + toUTF8String(filename));

3. 项目配置

3.1 springmvc-servlet.xml

3.2 web.xml

springmvc
org.springframework.web.servlet.DispatcherServlet
1
springmvc
/
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
characterEncodingFilter
/*

3.3 index.jsp

    
文件上传
选择文件1:
选择文件2:
选择文件3:
选择文件4:
选择文件5:

3.4 showDownFiles.jsp

    下载文件    

3.5 success.jsp

    成功    
  • ${file.originalFilename}

4. 注意事项

  • 确保所有文件都存放在 /fileUpload/temp/ 目录下。
  • 使用 UTF-8 编码来确保文件名的正确显示。
  • 测试时,确保浏览器的字符编码设置为 UTF-8。
  • 如果出现乱码问题,请检查 toUTF8String 方法是否正确。
  • 确保所有配置文件路径正确,避免文件存储位置错误。
  • 5. 运行测试

  • 打开浏览器访问 http://localhost:8080/index.jsp
  • 选择文件并上传。
  • 浏览文件列表并点击下载链接。
  • 测试文件是否正确下载并保存到本地。
  • 通过以上步骤,您应该能够顺利实现文件上传和下载功能。如果有任何问题,请仔细检查配置文件和代码,确保所有设置正确无误。

    转载地址:http://kmzx.baihongyu.com/

    你可能感兴趣的文章
    Openlayers:DMS-DD坐标形式互相转换
    查看>>
    openlayers:圆孔相机根据卫星经度、纬度、高度、半径比例推算绘制地面的拍摄的区域
    查看>>
    OpenLDAP(2.4.3x)服务器搭建及配置说明
    查看>>
    OpenLDAP编译安装及配置
    查看>>
    Openmax IL (二)Android多媒体编解码Component
    查看>>
    OpenMCU(一):STM32F407 FreeRTOS移植
    查看>>
    OpenMCU(三):STM32F103 FreeRTOS移植
    查看>>
    OpenMCU(三):STM32F103 FreeRTOS移植
    查看>>
    OpenMCU(二):GD32E23xx FreeRTOS移植
    查看>>
    OpenMCU(五):STM32F103时钟树初始化分析
    查看>>
    OpenMCU(四):STM32F103启动汇编代码分析
    查看>>
    OpenMetadata 命令执行漏洞复现(CVE-2024-28255)
    查看>>
    OpenMMLab | AI玩家已上线!和InternLM解锁“谁是卧底”新玩法
    查看>>
    OpenMMLab | S4模型详解:应对长序列建模的有效方法
    查看>>
    OpenMMLab | 【全网首发】Llama 3 微调项目实践与教程(XTuner 版)
    查看>>
    OpenMMLab | 不是吧?这么好用的开源标注工具,竟然还有人不知道…
    查看>>
    OpenMMLab | 面向多样应用需求,书生·浦语2.5开源超轻量、高性能多种参数版本
    查看>>
    OpenMP 线程互斥锁
    查看>>
    OpenMV入门教程(非常详细)从零基础入门到精通,看完这一篇就够了
    查看>>
    OpenObserve云原生可观测平台本地Docker部署与远程访问实战教程
    查看>>